package com.itheima.health.security;

import com.alibaba.fastjson.JSON;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class HealthSecurityFilter implements Filter {

    private String[] authUrl=new String[]{
            "/common/**",
            "/user/login","/user/logout",
            "/mobile/login/**"
            };
    private Map<String,String> loginAccessMap=new HashMap<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //初始化权限集合
        initAccessMap();
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取uri
        String uri = request.getRequestURI();
        log.info("[拦截请求]:uri:{}]",uri);
        //判断当前请求是否要拦截
        boolean isAuth=checkURI(uri);
        if (isAuth){
            log.info("允许放行");
            filterChain.doFilter(request,response);
            return;
        }
        //判断是否登录
        if (request.getSession().getAttribute("user")!=null){
            //已登录,获取权限,判断权限
            User user = (User)request.getSession().getAttribute("user");
            boolean isAccess= checkAccess(uri,user);
            if (isAccess){
                //有操作权限
                filterChain.doFilter(request,response);
            }else{
                //无操作权限
                response.setContentType("application/json; charset=UTF-8");
                response.getWriter().write(JSON.toJSONString(new Result(false, "无当前操作权限")));
            }
        }else{
            //未登录
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(new Result(false, "当前未登录")));
        }

    }

    @Autowired
    private UserService userService;

    //判断当前用户对该请求有无权限
    private boolean checkAccess(String uri, User user) {
        List<String> userAccess=userService.getUserAccess(user);
        log.info("[判断权限],用户权限:{},请求权限;{}",userAccess,loginAccessMap.get(uri));
        AntPathMatcher pathMatcher = new AntPathMatcher();
        Set<String> strings = loginAccessMap.keySet();
        for (String string : strings) {
            //log.info("[存储权限路径],string:{},uri:{}",string,uri);
            if (pathMatcher.match(string,uri)){
                if (userAccess.contains(loginAccessMap.get(string))){
                    log.info("[有权限通过],权限:{}",loginAccessMap.get(string));
                    return true;
                }else {
                    log.info("[无权限通过权限],权限:{}",loginAccessMap.get(string));
                    return false;
                }
            }
        }
        log.info("[该请求默认通过权限],uri:{}",uri);
        return true;
    }

    private void initAccessMap() {

        loginAccessMap.put("/checkitem/findPage","CHECKITEM_QUERY");
        loginAccessMap.put("/checkitem/findById","CHECKITEM_QUERY");
        loginAccessMap.put("/checkitem/edit","CHECKITEM_EDIT");
        loginAccessMap.put("/checkitem/delete","CHECKITEM_DELETE");
        loginAccessMap.put("/checkitem/add","CHECKITEM_ADD");
        loginAccessMap.put("/checkitem/findAll","CHECKITEM_QUERY");

        loginAccessMap.put("/checkgroup/findPage","CHECKGROUP_QUERY");
        loginAccessMap.put("/checkgroup/findById","CHECKGROUP_QUERY");
        loginAccessMap.put("/checkgroup/findCheckItemIdsByCheckGroupId","CHECKGROUP_QUERY");
        loginAccessMap.put("/checkgroup/edit","CHECKGROUP_EDIT");
        loginAccessMap.put("/checkgroup/add","CHECKGROUP_ADD");
        loginAccessMap.put("/checkgroup/delete","CHECKGROUP_DELETE");
        loginAccessMap.put("/checkgroup/deleteCheckGroupitemById","CHECKGROUP_DELETE");

        loginAccessMap.put("/setmeal/delete","SETMEAL_DELETE");

        loginAccessMap.put("/report/**","REPORT_VIEW");
    }

    private boolean checkURI(String uri) {
        //新建类来匹配通配符
        AntPathMatcher pathMatcher = new AntPathMatcher();
        for (String url : authUrl) {
            if ( pathMatcher.match(url,uri)){
                return true;
            }
        }
        return false;
    }


}
